﻿var siteId;
var productId;
var inventoryUrl = '/WebPages/Inventory.aspx?product=' + productId;

/* ************************ Initialize ************************ */
$j(function () {
    $j("#appendOptionRule").click(function () {
        var querystring = "?productId=" + productId + "&optionSet=" + $j("[id$='ddlOptionSetId']").val();
        if ($j("[id$='ddlUseInventory']").val() == 2) querystring = querystring + "&stock=" + $j("[id$='ddlUseInventory']").val();
        $j("#popupOptionRule").attr("href", "/WebPages/OptionRule.aspx" + querystring);
        $j("#popupOptionRule").trigger("click");
    });

    $j("#popupOptionRule").attr("href", "/WebPages/OptionRule.aspx?productId=" + productId + "&optionSet=" + $j("[id$='ddlOptionSetId']").val());

    $j("[id$='ddlOptionSetId']").change(function () {
        $j("#popupOptionRule").attr("href", "/WebPages/OptionRule.aspx?productId=" + productId + "&optionSet=" + $j(this).val());

        getOptionItems();
        getRules();

        GetOptionStock();
    });

    getOptionItems();

    getRules();

    $j("#popupOptionRule, #appendOptionSet").fancybox({
        width: "900px",
        height: "600px",
        fitToView: false,
        autoSize: false,
        openEffect: "fade",
        closeEffect: "fade"
    });

    $j(".trigger-inventory").fancybox({
        width: "800px",
        height: "400px",
        fitToView: false,
        autoSize: false,
        openEffect: "fade",
        closeEffect: "fade"
    });
});

/* ************************ Option Rule ************************ */
function changeNewSet(id, name) {
    $j("[id$='ddlOptionSetId']").append("<option value=\"" + id + "\">" + name + "</option>");
    $j("[id$='ddlOptionSetId']").val(id);
    $j("[id$='ddlOptionSetId']").trigger("change");
}
function getOptionItems() {
    var optionSetId = Number($j("[id$='ddlOptionSetId']").val());
    if (optionSetId != -1) {
        $j.ajax({
            type: "GET",
            dataType: "text",
            url: '/Admin/Services/GetOptions.ashx',
            data: "siteId=" + siteId + "&optionSetId=" + optionSetId,
            success: function (text) { $j("#rptOptionSetItem").html(text); },
            error: function (e) { console.log(e.message); }
        });
    }
}
function getRules() {
    var optionSetId = Number($j("[id$='ddlOptionSetId']").val());
    $j.ajax({
        type: "POST",
        url: "/WebServices/OptionService.asmx/GetRuleByProductId",
        data: "{'productid':'" + productId + "', 'optionsetid':'" + optionSetId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (response) {
            $j("#rptOptionRule").html(response.d);
            $j("#rptOptionRule").sortable({
                placeholder: "ui-state-highlight",
                update: function (event, ui) {
                    UpdateOrderNumberOptionRule();
                }
            });
            $j(".option-enabled input[type='checkbox']").change(function () {
                var ruleid = Number($j(this).attr("ruleid"));
                var checked = -1;
                if ($j(this).attr("checked") == "checked") { checked = 1; }
                else { checked = 0 }
                $j.ajax({
                    type: "POST",
                    url: "/WebServices/OptionService.asmx/EnabledOptionRule",
                    data: "{'optionRuleId':'" + ruleid + "','enabled':'" + checked + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response.d == "1") { }
                        else { alert("Bạn không có quyền thực hiện chức năng này!"); }
                    }
                });
            });
            $j(".option-actions a").each(function () {
                $j(this).click(function () {
                    var ruleid = Number($j(this).attr("ruleid"));
                    if ($j(this).attr("action") == "edit") {
                        $j("#popupOptionRule").attr("href", "/WebPages/OptionRule.aspx?productId=" + productId + "&optionSet=" + $j("[id$='ddlOptionSetId']").val() + "&ruleId=" + ruleid);
                        $j("#popupOptionRule").trigger("click");
                    }
                    else {
                        if ($j(this).attr("action") == "delete") {
                            var isDelete = confirm('Chắc chắn xóa thông tin này?');
                            if (isDelete) {
                                $j.ajax({
                                    type: "POST",
                                    url: "/WebServices/OptionService.asmx/DeleteOptionRule",
                                    data: "{'optionRuleId':'" + ruleid + "'}",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    success: function (response) {
                                        if (response.d == "1") {
                                            $j("#optionrule" + ruleid).fadeTo("fast", 0, function () {
                                                $j(this).slideUp("fast", function () { $j(this).remove(); });
                                            });
                                        }
                                        else { alert("Bạn không có quyền thực hiện chức năng này!"); }
                                    }
                                });
                            }

                        }
                    }
                });
            });
        },
        failure: function (msg) { console.log(msg); }
    });
}
function deleteRules() {
    $j.ajax({
        type: "POST",
        url: "/WebServices/OptionService.asmx/DeleteOptionRuleByProductId",
        data: "{'productId':'" + productId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (response) {
            if (Number(response.d == "1")) { }
            else { console.log(response.d); }
        },
        failure: function (msg) { console.log(msg); }
    });
}
function UpdateOrderNumberOptionRule() {
    $j("#rptOptionRule .option-item").each(function (i, obj) {
        var ruleid = $j(this).attr("id").replace("optionrule", "");
        $j.ajax({
            type: "POST",
            url: "/WebServices/OptionService.asmx/UpdateOrderNumberOptionRule",
            data: "{'optionRuleId':'" + ruleid + "','orderNumber':'" + i + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d == "1") { }
                else { console.log(response.d.ValueReturn); }
            }
        });
    });
}

/* ************************ Option Stock ************************ */
function AppendOptionStock()
{
    var href = inventoryUrl + '&optionset=' + $j("[id$='ddlOptionSetId']").val();
    $j('.trigger-inventory').attr('href', href).trigger('click');
}
function EditOptionStock(stock)
{
    var href = inventoryUrl + '&optionset=' + $j("[id$='ddlOptionSetId']").val() + '&stock=' + stock;
    $j('.trigger-inventory').attr('href', href).trigger('click');
}
function RemoveOptionStock(obj)
{
    if (confirm('Chắc chắn xóa thông tin quản lý kho theo bộ tùy chọn này?') == false) return;
    var stockId = $j(obj).attr('stock');
    if (stockId > 0) {
        $j.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "/WebServices/OptionService.asmx/DeleteOptionStockById",
            data: "{'stockId':'" + stockId + "'}",
            success: function (response) {
                $j(obj).parent().parent().fadeTo("fast", 0, function () {
                    $j(this).slideUp("fast", function () {
                        $j(this).remove();
                    });
                });
            }
        });
    }
}
function GetOptionStock() {
    var optionSetId = Number($j("[id$='ddlOptionSetId']").val());
    $j.ajax({
        type: "POST",
        url: "/WebServices/OptionService.asmx/GetOptionStock",
        data: "{'productId':'" + productId + "', 'optionSetId':'" + optionSetId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (response) {
            $j('#optionStocks').html(response.d);
        },
        failure: function (msg) { console.log(msg); }
    });
}

/* ************************ Option Stock ************************ */
var mediaDomainName;
var currentFolderImage;
function InitEditor(editorId) {
    var ckeditor = CKEDITOR.replace(editorId, {
        toolbar: [
            ['Source'], '-',
            ['Preview'], '-',
            ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'], '-',
            ['Undo', 'Redo', 'RemoveFormat'],
            ['Bold', 'Italic', 'Underline'], '-',
            ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], '-',
            ['Link', 'Unlink'], '-',
            ['Image', 'Flash', 'Table', 'Iframe'], '-',
            ['Styles', 'Format', 'Font', 'FontSize'], '-',
            ['TextColor', 'BGColor']
        ],
        language: 'vi',
        height: 300,
        contentsCss: '/Css/ckeditor.css',
        resize_enabled: false,
        toolbarCanCollapse: false,
        pasteFromWordRemoveStyles: false,
        filebrowserImageBrowseUrl: '/Extensions/FileBrowsers/BizFinder.aspx',
        filebrowserFlashBrowseUrl: '/Extensions/FileBrowsers/BizFinder.aspx?Type=Flash',
        filebrowserImageUploadUrl: '/Extensions/FileBrowsers/BizFinder.aspx?Type=Upload&currentFolder=' + currentFolderImage,
        filebrowserFlashUploadUrl: '/Extensions/FileBrowsers/BizFinder.aspx?Type=Flash'
        //filebrowserImageBrowseUrl: '/Extensions/ckfinder.2.3.1/ckfinder.html?mediadomain=' + mediaDomainName,
        //filebrowserFlashBrowseUrl: '/Extensions/ckfinder.2.3.1/ckfinder.html?Type=Flash&mediadomain=' + mediaDomainName,
        //filebrowserImageUploadUrl: '/Extensions/ckfinder.2.3.1/core/connector/aspx/connector.aspx?command=QuickUpload&type=Upload&currentFolder=' + currentFolderImage + '&mediadomain=' + mediaDomainName,
        //filebrowserFlashUploadUrl: '/Extensions/ckfinder.2.3.1/core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash&mediadomain=' + mediaDomainName
    });
}
function AppendPTabRow(id) {
    var ptab =
        '<div class="ptab_row">' +
            '<span class="key">Tên Tab hiển thị:</span>' +
            '<input id="txt_description_name_' + id + '" type="text" name="ptab_name_' + id + '" value="" />' +
            '<span class="del-command">' +
                '<input type="button" class="toolbar btn btn-info" value="Xóa" onclick="DeleteProductTab(' + id + ', this)" />' +
            '</span>' +
            '<br />' +
            '<textarea id="ck_description_' + id + '" name="ptab_desc_' + id + '" rows="3" cols="10"></textarea>' +
        '</div>';
    $j('#ptab_container').append(ptab);
    InitEditor('ck_description_' + id + '');
}
function DeleteProductTab(id, obj) {
    var res = confirm('Xóa thông tin Tab sản phẩm này?');
    if (res == true) {
        if (id > 0) {
            $j.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url: "/WebServices/ProductService.asmx/DeleteProductDesc",
                data: "{'id':'" + id + "', 'siteId':'" + siteId + "'}",
                success: function (response) {
                    $j(obj).parent().parent().fadeTo("fast", 0, function () {
                        $j(this).slideUp("fast", function () {
                            $j(this).remove();
                        });
                    });
                }
            });
        }
        else {
            $j(obj).parent().parent().fadeTo("fast", 0, function () {
                $j(this).slideUp("fast", function () {
                    $j(this).remove();
                });
            });
        }
    }
    return false;
}
$j(function () {
    var currentId = -1;
    $j("#tabs-7 textarea").each(function () {
        var editorId = $j(this).attr('id');
        InitEditor(editorId);
    });
    $j('#btnAddProductTab').click(function () {
        var length = $j('.ptab_row').length;
        if (length < 3) {
            AppendPTabRow(currentId);
            currentId = currentId - 1;
        }
        else {
            alert('Chỉ thêm được tối đa 3 tab sản phẩm!');
        }
        return false;
    });
});